package com.dodoke.framework.web.service;

import javax.annotation.Resource;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dodoke.common.config.WechatConfig;
import com.dodoke.common.core.domain.entity.SysWechatUserDO;
import com.dodoke.common.core.domain.model.LoginWechatBody;
import com.dodoke.framework.manager.AsyncManager;
import com.dodoke.framework.manager.factory.AsyncFactory;
import com.dodoke.framework.security.wechat.token.WechatAuthenticationToken;
import com.dodoke.system.service.ISysWechatUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.dodoke.common.constant.Constants;
import com.dodoke.common.core.domain.model.LoginUser;
import com.dodoke.common.core.redis.RedisCache;
import com.dodoke.common.exception.CustomException;
import com.dodoke.common.exception.user.CaptchaException;
import com.dodoke.common.exception.user.CaptchaExpireException;
import com.dodoke.common.exception.user.UserPasswordNotMatchException;
import com.dodoke.common.utils.MessageUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录校验方法
 * 
 * @author dodoke
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysWechatUserService sysWechatUserService;

    @Autowired
    private WechatConfig wechatConfig;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 微信小程序登录验证
     */
    public Map<String,String> wechatLogin(LoginWechatBody wechatBody) {

        SysWechatUserDO wechatUser = new SysWechatUserDO();
        wechatUser.setLanguage(wechatBody.getLanguage());
        wechatUser.setCountry(wechatBody.getCountry());
        wechatUser.setGender(wechatBody.getGender());
        wechatUser.setCity(wechatBody.getCity());
        wechatUser.setNickName(wechatBody.getNickName());
        wechatUser.setProvince(wechatBody.getProvince());


        String url = "https://api.weixin.qq.com/sns/jscode2session";

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", wechatConfig.getAppId());
        paramMap.put("secret", wechatConfig.getAppSecret());
        paramMap.put("js_code", wechatBody.getJsCode());
        paramMap.put("grant_type", "authorization_code");

        String rs = HttpUtil.get(url, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(rs);
        if(jsonObject.get("errcode") == null) {
            String openid = (String) jsonObject.get("openid");
            wechatUser.setOpenId(openid);

            SysWechatUserDO userDO = sysWechatUserService.selectSysWechatUserByOpenId(openid);
            if(userDO == null) {
                sysWechatUserService.insertSysWechatUser(wechatUser);
            }

            // 用户验证
            Authentication authentication = null;
            try {
                // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
                authentication = authenticationManager
                        .authenticate(new WechatAuthenticationToken(wechatUser.getOpenId(), ""));
            } catch (Exception e) {
                if (e instanceof BadCredentialsException) {
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(wechatUser.getNickName(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                    throw new UserPasswordNotMatchException();
                } else {
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(wechatUser.getNickName(), Constants.LOGIN_FAIL, e.getMessage()));
                    throw new CustomException(e.getMessage());
                }
            }
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(wechatUser.getNickName(), Constants.LOGIN_SUCCESS, MessageUtils.message("wechatuser.login.success")));
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            // 生成token
            Map<String, String> map = new HashMap<>(16);
            String token = tokenService.createToken(loginUser);
            map.put("token",token);
            map.put("openId",openid);
            return map;
        } else {
            int errcode = (int)jsonObject.get("errcode");
            if(errcode == -1) {
                throw new CustomException("系统繁忙，请稍候再试");
            } else if(errcode == 40029) {
                throw new CustomException("code 无效");
            } else if(errcode == 45011) {
                throw new CustomException("频率限制，每个用户每分钟100次");
            } else {
                throw new CustomException((String)jsonObject.get("errmsg"));
            }
        }

    }
}
